<?php
namespace Common\Logic;

/**
 * 客栈预定端相关逻辑
 * @modify trainyao 2016-04-27 创建
 */
class HotelBookLogic extends \Common\Controller\BaseController {

    private $userCouponType = array(
        'zh_cn' => array(
            USER_COUPON_NOT_USE => '未使用',
            USER_COUPON_USED => '已使用',
            USER_COUPON_CANCELED => '已失效',
            USER_COUPON_OUTDATED => '已过期',
        ),
        'en_us' => array(
            USER_COUPON_NOT_USE => 'Unused',
            USER_COUPON_USED => 'Used',
            USER_COUPON_CANCELED => 'Invalid',
            USER_COUPON_OUTDATED => 'Expired',
        ),
        'zh_tw' => array(
            USER_COUPON_NOT_USE => '未使用',
            USER_COUPON_USED => '已使用',
            USER_COUPON_CANCELED => '已失效',
            USER_COUPON_OUTDATED => '已過期',
        ),
    );


    /**
     * 检查是否已经开通
     * @modify trainyao 2016-04-27 创建
     * @param  integer   $hotelId   客栈ID
     * @return boolean              开通返回true,未开通返回false
     */
    public function checkEnable($hotelId, $onlyCheckExist = true) {
        $hotelDetailModel = D('HotelDetail');
        $hotelDetail = $hotelDetailModel->getInfoByHotel($hotelId);
        if (empty($hotelDetail)) {
            return false;
        }
        if ($hotelDetail['enable'] != ENABLE) {
            return false;
        }
        if (! $onlyCheckExist) {
            if ($hotelDetail['opened'] != ENABLE) {
                return false;
            }
            if (time() > strtotime($hotelDetail['enddate'])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查是否能上架房间
     * 该方法会抛异常
     * @modify trainyao 2016-05-12 创建
     * @param  integer   $hotelId   客栈ID
     * @return boolean              是否可以
     */
    public function checkCanEnableRoomType($hotelId) {
        $isEnable = $this->checkEnable($hotelId);
        if (!$isEnable) {
            throw new \Exception('403,409', 409);
            return false;
        }

        // 检查客栈姓名是否已初始化
        $hotelInfo = $this->getInfo($hotelId);
        if (empty($hotelInfo['name'])) {
            throw new \Exception('403,411', 411);
            return false;
        }
        return true;
    }

    /**
     * 开通微预定
     * @modify trainyao 2016-04-27 创建
     * @modify wenhui 2017-05-25 添加区号
     * @param  integer   $hotelId   客栈ID
     * @return Boolean              执行结果
     */
    public function enableBook($hotelId, $name, $contact, $mobile, $address, $description, $orderTimeout, $longtitude, $latitude, $telephone, $wechat, $hotline, $enddate, $areaCode = '86') {
        $hotelDetailModel = D('HotelDetail');
        $hotelDetailInfo = $hotelDetailModel->getInfoByHotel($hotelId);
        $hotelDetailModel->startTrans();
        $commit = true;
        
        if(empty($hotelDetailInfo)){
            $data = array(
                'hotelentity_id' => $hotelId,
                'name' => $name,
                'contact' => $contact,
                'areacode' => $areaCode,
                'mobile' => $mobile,
                'address' => $address,
                'description' => $description,
                'ordertimeout' => $orderTimeout,
                'enddate' => $enddate,
                'enable' => 1,
            );
            if(isset($longtitude)){
                $data['longtitude'] = $longtitude;
            }
            if(isset($latitude)){
                $data['latitude'] = $latitude;
            }
            if(isset($telephone)){
                $data['telephone'] = $telephone;
            }
            if(isset($wechat)){
                $data['wechat'] = $wechat;
            }
            if(isset($hotline)){
                $data['hotline'] = $hotline;
            }
            $enableResult = $hotelDetailModel->add($data);
        }
        if (empty($enableResult)) {
            $commit = false;
        }

        if ($commit) {
            $hotelPayDetailModel = D('HotelPayDetail');
            $enableResult = $hotelPayDetailModel->addInfo($hotelId);
            if (empty($enableResult)) {
                $commit = false;
            }
        }

        if ($commit) {
            $hotelDetailModel->commit();
            return true;
        } else {
            $hotelDetailModel->rollback();
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 获取客栈预定信息
     * @modify trainyao 2016-04-28 创建
     * @param  integer   $hotelId   客栈id
     * @param  integer   $bookLangSet   微预定语言设置
     * @return array              客栈信息数组,失败返回空数组
     */
    public function getInfo($hotelId, $brief = false, $bookLangSet = null) {
        // 获取基本信息
        $hotelDetailModel = D('HotelDetail');
        $hotelDetail = $hotelDetailModel->getInfoByHotel($hotelId);
        if (empty($hotelDetail)) {
            return array();
        }
        if ($brief !== false) {
            return $hotelDetail;
        }

        // 获取设施信息
        $hotelFacilityModel = D('HotelFacility');
        $hotelFacilityInfo = $hotelFacilityModel->getInfoByHotel($hotelId);
        $hotelFacilityIds = array_column($hotelFacilityInfo, 'facility_id');
        // 处理客栈哪些设施有,哪些没有
        $facilityModel = D('Facility');
        $facilityInfo = $facilityModel->getInfo();
        $LangSet = !is_null($bookLangSet) ? $bookLangSet : LANG_SET;
        foreach ($facilityInfo as &$facilityInfoItem) {
            $facilityInfoItem['enable'] = in_array($facilityInfoItem['id'], $hotelFacilityIds) ? ENABLE : DISABLE;
            switch ($LangSet) {
                case 'zh_cn':
                    $facilityInfoItem['name'] = explode('/', $facilityInfoItem['name'])[0];
                    break;
                case 'en_us':
                    $facilityInfoItem['name'] = ucwords(explode('/', $facilityInfoItem['name'])[1]);
                    break;
                case 'zh_tw':
                    $facilityInfoItem['name'] = explode('/', $facilityInfoItem['name'])[2];
                    break;
                default:
                    $facilityInfoItem['name'] = explode('/', $facilityInfoItem['name'])[0];
                    break;
            }
        }
        unset($facilityInfoItem);
        $hotelDetail['facility'] = $facilityInfo;

        // 系统推荐标签
        $specialTagModel = D('SpecialTag');
        $defaultSpecialTag = $specialTagModel->getInfo();
        $defaultSpecialTag = array_column($defaultSpecialTag, 'name');
        $hotelDetail['specialTag'] = array();
        foreach ($defaultSpecialTag as $key => $defaultSpecialTagItem) {
            $hotelDetail['specialTag'][$defaultSpecialTagItem] = array(
                'id' => 0,
                'name' => $defaultSpecialTagItem,
                'isDefault' => 1,
                'enable' => DISABLE,
            );
        }
        unset($defaultSpecialTagItem);

        // 获取推荐标签,处理数据
        $hotelSpecialTagModel = D('HotelSpecialTag');
        $hotelSpecialTagInfo = $hotelSpecialTagModel->getInfoByHotel($hotelId);
        if (!empty($hotelSpecialTagInfo)) {
            foreach ($hotelSpecialTagInfo as $key => $hotelSpecialTagInfoItem) {
                if (isset($hotelDetail['specialTag'][$hotelSpecialTagInfoItem['name']])) {
                    $hotelDetail['specialTag'][$hotelSpecialTagInfoItem['name']]['enable'] = ENABLE;
                    $hotelDetail['specialTag'][$hotelSpecialTagInfoItem['name']]['id'] = $hotelSpecialTagInfoItem['id'];
                } else {
                    $hotelDetail['specialTag'][$hotelSpecialTagInfoItem['name']] = array(
                        'id' => $hotelSpecialTagInfoItem['id'],
                        'name' => $hotelSpecialTagInfoItem['name'],
                        'isDefault' => 0,
                        'enable' => ENABLE,
                    );
                }
            }
            unset($hotelSpecialTagInfoItem);
        }
        $hotelDetail['specialTag'] = array_values($hotelDetail['specialTag']);

        // 获取客栈图册
        $hotelPictureModel = D('HotelPicture');
        $hotelPictureInfo = $hotelPictureModel->getInfoByHotel($hotelId);
        $hotelDetail['gallery'] = $hotelPictureInfo;

        // 获取客栈图标
        $hotelAuthModel = D('HotelAuth');
        $hotelPayUsableModel = D('HotelPayUsable');
        $hotelEntityModel = D('HotelEntity');
        $hotelAppModel = D('HotelApp');
        $hotelPayDetailModel = D('HotelPayDetail');

        $hotelAuthInfo = $hotelAuthModel->getInfo($hotelId);
        $hotelPayUsableInfo = $hotelPayUsableModel->getInfo($hotelId);
        $hotelEntityInfo = $hotelEntityModel->getInfo($hotelId);
        $hotelAppInfo = $hotelAppModel->getInfo($hotelId);
        $hotelPayDetailInfo = $hotelPayDetailModel->getInfoByHotel($hotelId);

        // 微预定认证状态
        $certifiedenddate = strtotime($hotelDetail['certifiedenddate']) > strtotime(date('Y-m-d')) ? true : false;
        $hotelAuthenticateStatus = $hotelAuthInfo['status'] == '2' && $certifiedenddate ? true : false;

        // 畅联代收状态
        $uclbrtalipayenable = strtotime($hotelPayUsableInfo['uclbrtalipayenddate']) > strtotime(date('Y-m-d')) && $hotelPayUsableInfo['uclbrtalipayenable'] == '1' ? true : false;
        $uclbrtwechatenable = strtotime($hotelPayUsableInfo['uclbrtwechatenddate']) > strtotime(date('Y-m-d')) && $hotelPayUsableInfo['uclbrtwechatenable'] == '1' ? true : false;
        $hotelUclbrtEnable = $uclbrtalipayenable || $uclbrtwechatenable ? true : false;

        // 商家自收、保障金状态
        $hotelalipaysafeguard = strtotime($hotelPayUsableInfo['hotelalipayenddate']) > strtotime(date('Y-m-d')) && $hotelPayUsableInfo['hotelalipaysafeguard'] == '1' && $hotelPayUsableInfo['hotelalipayenable'] == '1' ? true : false;
        $hotelwechatsafeguard = strtotime($hotelPayUsableInfo['hotelwechatenddata']) > strtotime(date('Y-m-d')) && $hotelPayUsableInfo['hotelwechatsafeguard'] == '1' && $hotelPayUsableInfo['hotelwechatenable'] == '1' ? true : false;
        $hotelSafeguardStatus = $hotelalipaysafeguard || $hotelwechatsafeguard ? true : false;

        // 美住web开通状态
        $hotelEntityenddate = strtotime($hotelEntityInfo['enddate']) > strtotime(date('Y-m-d')) ? true : false;
        $hotelUsageStatus = $hotelEntityInfo['usage'] == '1' && $hotelEntityenddate ? true : false;

        // 美住app开通状态
        $hotelAppenddate = strtotime($hotelAppInfo['enddate']) > strtotime(date('Y-m-d')) ? true : false;
        $hotelAppStatus = $hotelAppInfo['status'] == '1' && $hotelAppenddate ? true : false;

        $hotelDetail['hotelIcon'] = array(
            'hotelIcon' => $hotelUsageStatus && $hotelAuthenticateStatus, // 是否显示认证图标
            'hotelSafeguardIcon' => $hotelUsageStatus && $hotelSafeguardStatus, // 是否显示保障金图标
            'hotelCreditIcon' => $hotelUsageStatus && $hotelUclbrtEnable ? true : false, // 是否显示诚信交易图标
            'hotelBrandIcon' => $hotelUsageStatus && $hotelAppStatus && ($hotelUclbrtEnable || $hotelSafeguardStatus) ? true : false, // 是否显示优质品牌客栈图标
        );

        return $hotelDetail;
    }

    /**
     * 保存或新建客栈预定端信息
     * @modify trainyao 2015-12-31    创建
     * @modify wenhui 2017-05-04 增加国际手机区号
     * @param  integer   $hotelId      客栈id
     * @param  array   $facilityId         客栈设施id数组
     * @param  string   $name         客栈名
     * @param  string   $description  掌柜说(客栈描述)
     * @param  string   $contact      客栈联系人
     * @param  string   $mobile       联系人手机号
     * @param  string   $telephone      前台电话
     * @param  string   $wechat         微信号
     * @param  string   $hotline         投诉热线
     * @param  string   $address     具体地址
     * @param  string   $longtitude    经度
     * @param  string   $latitude       纬度
     * @param  string   $orderTimeOut  预定订单过期时间
     * @param  string   $areaCode  区号
     * @return boolean 保存或新建结果
     */
    public function saveDetail($hotelId, $facilityId = null, $name = null, $description = null, $contact = null, $mobile = null, $telephone = null, $wechat = null, $address = null, $longtitude = null, $latitude = null, $orderTimeOut = null, $hotline = null, $logoImageUrl  = null, $areaCode = '86') {
        // 校验设施id是否有效
        if (!is_null($facilityId)) {
            $facilityModel = D('Facility');
            $facilityInfo = $facilityModel->getInfo();
            $enableFacilityIds = array_column($facilityInfo, 'id');
            if (!empty(array_diff($facilityId, $enableFacilityIds))) {
                returnJson(403, 202);
                return false;
            }
        }

        // 开始修改
        $hotelDetailModel = D('HotelDetail');
        $hotelDetailModel->startTrans();
        $commit = true;

        // 保存客栈基本资料
        $saveResult = $hotelDetailModel->saveInfo($hotelId, $name, $description, null, null, null, $contact, $mobile, $telephone, $wechat, $address, $longtitude, $latitude, $orderTimeOut, null, $hotline, $logoImageUrl, $areaCode);
        if (empty($saveResult)) {
            $commit = false;
        }

        if ($commit && !is_null($facilityId)) {
            // 保存客栈设施
            $hotelDetail = $this->getInfo($hotelId);
            $currentFacilityId = array();
            foreach ($hotelDetail['facility'] as $facilityItem) {
                if ($facilityItem['enable'] == ENABLE) {
                    array_push($currentFacilityId, $facilityItem['id']);
                }
            }
            unset($facilityItem);
            $facilityToDelete = array_diff($currentFacilityId, $facilityId);
            $facilityToAdd = array_diff($facilityId, $currentFacilityId);

            $hotelFacilityModel = D('HotelFacility');
            if (!empty($facilityToAdd)) {
                $saveResult = $hotelFacilityModel->addInfo($hotelId, $facilityToAdd);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }
            if ($commit && !empty($facilityToDelete)) {
                $saveResult = $hotelFacilityModel->deleteInfoByHotel($hotelId, $facilityToDelete);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            $hotelDetailModel->commit();
            return true;
        } else {
            $hotelDetailModel->rollback();
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 保存客栈图册
     * @modify trainyao 2016-04-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  array   $urls      图册url数组
     * @return boolean            执行结果
     */
    public function saveGallery($hotelId, $urls) {
        $hotelDetail = $this->getInfo($hotelId);
        $hotelToDelete = $hotelDetail['gallery'];

        // 处理传入数据
        $urlToAdd = array();
        foreach ($urls as $url) {
            $urlToAdd[$url] = 1;
        }
        unset($url);
        unset($urls);

        // 取出数据库内存在,也传进来的url
        foreach ($hotelToDelete as $index => $hotelToDeleteItem) {
            if (isset($urlToAdd[$hotelToDeleteItem['name']])) {
                unset($hotelToDelete[$index]);
                unset($urlToAdd[$hotelToDeleteItem['name']]);
            }
        }
        unset($hotelToDeleteItem);

        $hotelPictureModel = D('HotelPicture');
        $hotelPictureModel->startTrans();
        $commit = true;

        // 删除图册
        if (!empty($hotelToDelete)) {
            $hotelToDelete = array_column($hotelToDelete, 'id');
            $saveResult = $hotelPictureModel->deleteInfo($hotelToDelete);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        // 插入图册
        if ($commit && !empty($urlToAdd)) {
            $urlToAdd = array_keys($urlToAdd);
            $saveResult = $hotelPictureModel->addInfo($hotelId, $urlToAdd);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        if ($commit) {
            $hotelPictureModel->commit();
            return true;
        } else {
            $hotelPictureModel->rollback();
            returnJson(500, 506);
            return false;
        }
    }

    /**
     * 保存个性推荐信息
     * @modify trainyao 2016-04-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $special   个性推荐信息
     * @param  string   $url       个性推荐图片url
     * @param  array   $tag       个性推荐标签
     * @return boolean              执行结果
     */
    public function saveSpecialInfo($hotelId, $special = null, $url = null, $tag = null) {
        $hotelDetailModel = D('HotelDetail');
        $hotelDetailModel->startTrans();
        $commit = true;

        // 保存个性推荐信息
        $saveResult = $hotelDetailModel->saveInfo($hotelId, null, null, $special, $url, null, null, null, null, null, null, null, null, null);
        if (empty($saveResult)) {
            $commit = false;
        }

        if ($commit && !is_null($tag)) {
            // 保存推荐标签
            $tagToAdd = array();
            foreach ($tag as $tagItem) {
                $tagToAdd[$tagItem] = 1;
            }
            unset($tagItem);
            unset($tag);

            $hotelDetail = $this->getInfo($hotelId);
            $hotelSpecialToDelete = $hotelDetail['specialTag'];

            // 取出数据库存在的不需要处理的
            foreach ($hotelSpecialToDelete as $index => $hotelSpecialTagItem) {
                // 删除未选中的
                if ($hotelSpecialTagItem['enable'] == DISABLE) {
                    unset($hotelSpecialToDelete[$index]);
                    continue;
                }

                if (isset($tagToAdd[$hotelSpecialTagItem['name']])) {
                    unset($hotelSpecialToDelete[$index]);
                    unset($tagToAdd[$hotelSpecialTagItem['name']]);
                }
            }
            unset($hotelSpecialTagItem);

            $hotelSpecialTagModel = D('HotelSpecialTag');
            // 删除标签
            if (!empty($hotelSpecialToDelete)) {
                $hotelSpecialToDelete = array_column($hotelSpecialToDelete, 'id');
                $saveResult = $hotelSpecialTagModel->deleteInfo($hotelSpecialToDelete);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }

            // 插入标签
            if ($commit && !empty($tagToAdd)) {
                $tagToAdd = array_keys($tagToAdd);
                $saveResult = $hotelSpecialTagModel->addInfo($hotelId, $tagToAdd);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            $hotelDetailModel->commit();
            return true;
        } else {
            $hotelDetailModel->rollback();
            returnJson(500, 506);
            return false;
        }
    }
    /**
     * 添加新的个性推荐信息
     * @modify wenhui 2016-10-28 创建
     * @modify wenhui 2017-30-07 检查是否存在掌柜说
     * @param  integer   $hotelId   客栈ID
     * @param  string   $url       个性推荐图片url
     * @param  bool   $version       移动端的版本判断 默认true
     * @return specialId              执行结果
     */
    public function addSpecialInfo($hotelId, $url, $version = true) {
        $hotelSpecialModel = D('HotelSpecial');

        // 保存新的个性推荐信息
        $specialId = $hotelSpecialModel->addInfo($hotelId, $url);
        if (empty($specialId)) {
            return false;
        }

        // 获取新添加的排序值 保存
        $hotelSpecialDetail = $hotelSpecialModel->getInfoByHotel($hotelId);
        $sortindexValeu = array_column($hotelSpecialDetail, 'sortindex');
        rsort($sortindexValeu, SORT_NUMERIC);
        $sortindexValeu = ++ $sortindexValeu[0];
        $hotelSpecialModel->saveInfo($hotelId, $specialId, null, null, $sortindexValeu);

        // 再获取掌柜说的信息
        $hotelSpecialInfo = $hotelSpecialModel->getSpecialInfoById($specialId);
        if ($version) {
            // 客栈没有设置掌柜说 则把新添加设为掌柜说
            $hotelSpecialManage = $hotelSpecialModel->getSpecials($hotelId);
            if (empty($hotelSpecialManage)) {
                $hotelSpecialModel->saveManage($specialId);
                // 再获取已设掌柜说的信息
                $hotelSpecialInfo = $hotelSpecialModel->getSpecialInfoById($specialId);        
                $data = array(
                    'specialId' => $specialId,
                    'isactive' => $hotelSpecialInfo['isactive'],
                    'specialImageUrl' => $hotelSpecialInfo['specialimageurl'],
                    'sortindex' => $hotelSpecialInfo['sortindex'],
                );
            } else {
                $data = array(
                    'specialId' => $specialId,
                    'isactive' => $hotelSpecialInfo['isactive'],
                    'specialImageUrl' => $hotelSpecialInfo['specialimageurl'],
                    'sortindex' => $hotelSpecialInfo['sortindex'],
                );
            }
        } else {
            $data = array(
                    'specialId' => $specialId,
                    //'isactive' => $hotelSpecialInfo['isactive'],
                    'specialImageUrl' => $hotelSpecialInfo['specialimageurl'],
                    //'sortindex' => $hotelSpecialInfo['sortindex'],
            );
        }

        return $data;
    }
    /**
     * 修改图片说明信息
     * @modify wenhui 2016-10-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $special   个性推荐信息
     * @param  integer   $specialId  个性推荐图片id
     * @return boolean              执行结果
     */
    public function saveSpecial($hotelId, $specialId, $url = null, $special = null ) {
        $hotelSpecialModel = D('HotelSpecial');

        // 保存新的个性推荐信息
        $saveResult = $hotelSpecialModel->saveInfo($hotelId, $specialId, $url, $special);
        if (!$saveResult) {
            return false;
        }
        return true;
    }
    /**
     * 删除个性推荐信息
     * @modify wenhui 2016-10-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  integer   $specialId  个性推荐图片id
     * @return boolean              执行结果
     */
    public function deleteSpecialInfos($specialId) {
        $hotelSpecialModel = D('HotelSpecial');

        //  删除个性推荐信息
        $deleteResult = $hotelSpecialModel->deleteInfo($specialId);
        if (!$deleteResult) {
            return false;
        }
        return true;
    }
    /**
     * 微预定设置 设置掌柜说
     * @modify wenhui 2016-10-28 创建
     * @param  integer   $hotelId   客栈ID
     * @param  integer   $specialId  个性推荐图片id
     * @param  integer   $index  索引值
     * @return boolean              执行结果
     */
    public function saveManageInfo($hotelId, $specialId, $index = null) {
        $hotelSpecialModel = D('HotelSpecial');

        // 旧的索引值
        $oldIndex = $hotelSpecialModel->getSpecials($hotelId)['sortindex'];
        if (empty($oldIndex)) {
            $oldIndex = null;
        }
        // 初始化 同一个酒店的掌柜说 isactive字段默认为零 即(isactive = 0 )
        $saveResult = $hotelSpecialModel->saveInit($hotelId, $index);
        if (!$saveResult) {
            return false;
        }

        // 设置掌柜说
        $saveResult = $hotelSpecialModel->saveManage($specialId, $oldIndex);
        if (!$saveResult) {
            return false;
        }

        return true;
    }
    /**
     * 获取多套个性推荐信息
     * @modify wenhui 2016-10-28 创建
     * @param  integer   $hotelId   客栈ID
     * @return $hotelSpecialDetail     执行结果
     */
    public function getSpecialInfo($hotelId) {
        $hotelSpecialModel = D('HotelSpecial');

        $hotelSpecialDetail = $hotelSpecialModel->getInfoByHotel($hotelId);
        if (empty($hotelSpecialDetail)) {
            return false;
        }

        return $hotelSpecialDetail;
    }
    /**
     * 通过specialId获取一套个性推荐信息
     * @modify wenhui 2016-10-28 创建
     * @param  mixed   $specialId   客栈ID
     * @return $data              执行结果
     */
    public function getOneSpecialInfo($specialId) {
        $hotelSpecialModel = D('HotelSpecial');

        $hotelSpecialDetail = $hotelSpecialModel->getSpecialInfoById($specialId);
        if (empty($hotelSpecialDetail)) {
            return false;
        }

        return $hotelSpecialDetail;
    }
    /**
     * 
     * @modify wenhui 2016-10-28 创建
     * @param  integer   $specialId   客栈ID
     * @return $data              执行结果
     */
    public function getSpecial($hotelId) {
        $hotelSpecialModel = D('HotelSpecial');

        $hotelSpecial = $hotelSpecialModel->getSpecials($hotelId);
        if (empty($hotelSpecial)) {
            return false;
        }

        return $hotelSpecial;
    }

    /**
     * 根据图片id删除客栈图册
     * @modify wenhui 2016-12-06 创建
     * @param  integer   $hotelPictureId   图片ID
     * @return boolean            执行结果
     */
    public function deleteImage($hotelPictureId) {
        if (is_null($hotelPictureId)) {
             return false;
        }

        $hotelPictureModel = D('HotelPicture');
        $saveResult = $hotelPictureModel->deleteInfo($hotelPictureId);
        if (empty($saveResult)) {
            return false;
        }

        return $saveResult;
    }

    /**
     * 根据客栈id，url 获取一条记录
     * @modify wenhui 2016-12-06  创建
     * @param  int   $hotel 客栈id
     * @param  string   $url
     * @return array               房型数据
     */
    public function getImageInfo($hotel = null, $url =null) {
        $HotelPictureModel = D('HotelPicture');
        $imageInfo = $HotelPictureModel->getImageInfo($hotel, $url);
        return $imageInfo === false ? false : $imageInfo;
    }

     /**
     * 掌柜说推送
     * @modify wenhui 2017-03-24 创建
     */
    public function pushManage($hotelId, $specialId, $indexs = null, $isSave = null) {
        $hotelSpecialModel = D('HotelSpecial');
        $hotelSpecialModel->startTrans();

        // 获取掌柜说描述
        $hotelSpecialDetail = $this->getOneSpecialInfo($specialId);
        if ($hotelSpecialDetail == false) {
            returnJson(403, 702, 'error');
        }

        if (is_array($hotelSpecialDetail[0])) {
            // 多套掌柜说的处理
            $special = '';
        } else {
            $special = !empty($hotelSpecialDetail['special']) ? $hotelSpecialDetail['special'] : '';
        }

        if (empty($special)) {
            returnJson(403, 706, 'error');
        }

        // 客栈名称
        $hotelInfo = D('HotelDetail')->getInfoByHotel($hotelId);
        $hotelName = isset($hotelInfo['name']) ? $hotelInfo['name'] : '';

        // 写入redis
        $redisUtil = new \Org\Util\RedisHelper(null, null, 'qrclient');
        $redisUtil->db(C('REDIS_MANAGE_PUSH_DB'))->table('manageNewsPush');

        $getResult = $redisUtil->exists($hotelId . '_push');
        $expireTime = 86400 - (time() - strtotime(date('Ymd')));
        if (!$getResult) {
            // 按一天推送一次
            $addKey = $redisUtil->hMSet($hotelId . '_push', array('pushCount' => 1), time()+$expireTime);
            $addKey = $redisUtil->hMSet($hotelId . '_canPush', array('canPushCount' => 1), time()+$expireTime);
            // 按缴费 决定推送次数 (可扩展)
            //$addKey = $redisUtil->hMSet($hotelId . 'push', array('pushCount' => 1));
            //$addKey = $redisUtil->hMSet($hotelId . 'canPush', array('canPushCount' => $canPushCount)); 缴费后的$canPushCount
        } else {
            $pushResult = $redisUtil->hMGet($hotelId . '_push');
            $canPushResult = $redisUtil->hMGet($hotelId . '_canPush');
            if ($pushResult['pushCount'] < $canPushResult['canPushCount']) {
                // 按缴费 决定推送次数 (可扩展)
                // 在支付的逻辑处理中 初始化Key值
                // $redisUtil->hMSet($hotelId . 'push', array('pushCount' => 0)); $redisUtil->hMSet($hotelId . 'canPush', array('canPushCount' => $canPushCount));
                //$pushCount = ++$pushResult['pushCount'];
                //$addKey = $redisUtil->hMSet($hotelId . 'push', array('pushCount' => $pushCount));
            } else {
                returnJson(403, 705);
            }
        }

        $commit = true;
        if (!is_null($indexs)) {

            // 重新排序掌柜说
            $indexValues = array_column($indexs,'index');
            // 校验索引值是否重复
            $indexValues = array_column($indexs, 'index');
            if (count($indexValues) != count(array_unique($indexValues))) {
                $commit = false;
            }

            if ($commit) {

                $hotelSpecialDetail = $hotelSpecialModel->getInfoByHotel($hotelId);
                $hotelSpecialDetail = getArrayValueAsIndex($hotelSpecialDetail, 'id');
                // 比较得出要执行修改语句的信息
                foreach ($indexs as $itemIndex => $indexToSaveItem) {
                    if (isset($hotelSpecialDetail[$indexToSaveItem['specialId']])) {
                        if ($hotelSpecialDetail[$indexToSaveItem['specialId']]['sortindex'] == $indexToSaveItem['index']) {
                            unset($indexs[$itemIndex]);
                        }
                    } else {
                        $commit = false;
                    }
                }
                unset($indexToSaveItem);

                if ($commit && !empty($indexs)) {
                    // 执行修改语句
                    foreach ($indexs as $indexToSaveItem) {
                        $sortResult = $hotelSpecialModel->saveInfo($hotelId, $indexToSaveItem['specialId'], null, null, $indexToSaveItem['index']);
                        if (!$sortResult) {
                            $commit = false;
                            break;
                        }
                    }
                    unset($indexToSaveItem);
                }
            }

        }

        if ($commit) {
            // 调用推送接口 app端
            $jpushConfig = C('JPUSH_CONFIG_QRCLIENT');
            vendor('jpush.autoload');
            $jpushUtil = new \JPush\Client($jpushConfig['appID'], $jpushConfig['appSecret'], $jpushConfig['logPath']);
            $push = $jpushUtil->push();
            $errorMsg = '';
            try {
                $push->setPlatform(array('ios', 'android'))
                    ->iosNotification(array('title' => $hotelName, 'body' => $special), array('sound' => 'sound.caf','extras' => array('hotel' => $hotelId)))
                    ->androidNotification($special, array('title' => $hotelName, 'extras' => array('hotel' => $hotelId)));
                // 查看是否在调试模式,如果是,消息只发送到测试tag的用户
                if ($jpushConfig['qrDebug']) {
                    $push->addTag($jpushConfig['debugTag']);
                    $push->options(array(
                        'apns_production' => false,
                    ));
                } else {
                    $push->addAllAudience();
                    $push->options(array(
                        'time_to_live' => 86400,
                    ));
                    $push->options(array(
                        'apns_production' => true,
                    ));
                }

                $result = $push->send();
            } catch (\JPush\Exceptions\APIConnectionException $e) {
                $errorMsg = $e->getMessage();
                \Think\Log::write($errorMsg . "\r\n", \Think\Log::ERR, '', $jpushConfig['logPath']);
            } catch (\JPush\Exceptions\APIRequestException $e) {
                $errorMsg = $e->getMessage();
                \Think\Log::write($errorMsg . "\r\n", \Think\Log::ERR, '', $jpushConfig['logPath']);
            } catch (\Exception $e) {
                $errorMsg = $e->getMessage();
                \Think\Log::write($errorMsg . "\r\n", \Think\Log::ERR, '', $jpushConfig['logPath']);
            }

            if ($result['http_code'] != '200') {
                $errorMsg = json_encode($result);
                \Think\Log::write($errorMsg . "\r\n", \Think\Log::ERR, '', $jpushConfig['logPath']);
                returnJson(403, 704, 'error');
            }

            // 移动端新版本设为封面
            if (!is_null($indexs)) {
                $this->saveManageInfo($hotelId, $specialId, null);
            }
            // web端设为封面
            if (!is_null($isSave)) {
                $this->saveManageInfo($hotelId, $specialId, null);
            }

            if ($result['http_code'] == '200' && $commit) {
                $hotelSpecialModel->commit();
                return true;
            }
        }

        $hotelSpecialModel->rollback();
        return false;
    }

    /**
     * 保存掌柜说排序
     * 方法会抛异常
     * @modify wenhui 2017-03-09 创建
     * @param  hotel   $userId    用户ID
     * @param  array   $indexToSave     [{
     *                                collectId, index
     *                            }, {}, {}, {}..]
     * @return boolean              执行结果
     */
    public function manageSortIndex($hotelId, $indexToSave) {
        $hotelSpecialModel = D('HotelSpecial');
        $hotelSpecialDetail = $hotelSpecialModel->getInfoByHotel($hotelId);

        $hotelSpecialDetail = getArrayValueAsIndex($hotelSpecialDetail, 'id');
        // 比较得出要执行修改语句的信息
        foreach ($indexToSave as $itemIndex => $indexToSaveItem) {
            if (isset($hotelSpecialDetail[$indexToSaveItem['specialId']])) {
                if ($hotelSpecialDetail[$indexToSaveItem['specialId']]['sortindex'] == $indexToSaveItem['index']) {
                    unset($indexToSave[$itemIndex]);
                }
            } else {
                // 传ID不可操作,报无权限
                throw new \Exception('403,418', 418);
                return false;
            }
        }
        unset($indexToSaveItem);

        if (empty($indexToSave)) {
            return true;
        }

        $hotelSpecialModel->startTrans();
        $commit = true;

        // 执行修改语句
        foreach ($indexToSave as $indexToSaveItem) {
            $sortResult = $hotelSpecialModel->saveInfo($hotelId, $indexToSaveItem['specialId'], null, null, $indexToSaveItem['index']);
            if (!$sortResult) {
                $commit = false;
                break;
            }
        }
        unset($indexToSaveItem);

        if ($commit) {
            $hotelSpecialModel->commit();
            return true;
        } else {
            $hotelSpecialModel->rollback();
            throw new \Exception('500,506', 506);
            return false;
        }
    }

    /**
     * 设置优惠券
     * @modify wenhui 2017-01-02    创建
     * @param  int   $hotelId    客栈ID
     * @param  string   $name    名称
     * @param  int   $couponType   优惠券类型 1=满减券 2=折扣券
     * @param  decimal   $price    满减金额
     * @param  int   $discount    折扣值
     * @param  int   $number    优惠券数量
     * @param  string   $startDate    开始时间
     * @param  string   $endDate    结束时间
     * @param  string   $week    禁用星期 array(1,2,3,4,5,6,0)
     * @param  array   $roomTypeIds    使用的房型id array(11,22,...)
     * @param  array   $disableDates    禁用具体日期 array('2018-01-02','2018-01-03'...)
     * @param  int   $useMan    使用人群 1=全部 2=会员 3=非会员
     * @param  decimal   $minusPrice    立减金额
     * @param  int   $useNumber    每个账号对该优惠券最多可领取次数
     * @param  int   $roomType    房间类型 1=间夜房 2=钟点房 3=长租房
     */
    public function addCoupon($hotelId, $name, $couponType, $price, $discount, $number, $startDate, $endDate, $week, $roomTypeIds, $disableDates, $useMan, $minusPrice, $useNumber, $roomType) {

        // 校验时间合法性
        if (!isBeforeTime($startDate, $endDate, true)) {
            returnJson(403, 317, 'error');
        }

        if (is_array($week)) {
            $week = implode(',', $week);
        }

        $hotelCouponModel = D('HotelCoupon');
        $hotelCouponRoomTypeModel = D('HotelCouponRoomType');
        $hotelCouponDisableDateModel = D('HotelCouponDisableDate');
        $hotelCouponModel->startTrans();
        $commit = true;

        $couponId = $addResult = $hotelCouponModel->addCoupon($hotelId, $name, $couponType, $price, $discount, $number, $startDate, $endDate, $week, $useMan, $minusPrice, $useNumber, $roomType);

        if (empty($addResult)) {
            $commit = false;
        }

        // 生成优惠券码
        $couponNo = encodeCouponNumber($couponId, 'CP');
        if ($commit) {
            $saveResult = $hotelCouponModel->saveCouponNo($couponId, $couponNo);
            if ($saveResult === false) {
                $commit = false;
            }
        }

        foreach ($roomTypeIds as $roomTypeId) {
            $addRoomTypeData[] = ['coupon_id' => $couponId, 'roomtype_id' => $roomTypeId];
        }
        unset($roomTypeId);

        foreach ($disableDates as $disableDate) {
            $addDisableDateData[] = ['coupon_id' => $couponId, 'date' => strtotime($disableDate)];
        }
        unset($disableDate);

        if ($commit && !empty($addRoomTypeData)) {
            $addResult = $hotelCouponRoomTypeModel->addCouponRoomType($addRoomTypeData);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        if ($commit && !empty($addDisableDateData)) {
            $addResult = $hotelCouponDisableDateModel->addCouponDisableDate($addDisableDateData);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        //事务提交回滚
        if ($commit) {
            $hotelCouponModel->commit();
            return true;
        } else {
            $hotelCouponModel->rollback();
            return false;
        }
    }

    /**
     * 设置优惠券
     * @modify wenhui 2017-01-02    创建
     * @param  int   $couponId    优惠券ID
     * @param  string   $name    名称
     * @param  string   $startDate    开始时间
     * @param  string   $endDate    结束时间
     * @param  string   $week    禁用星期 array(1,2,3,4,5,6,0)
     * @param  array   $roomTypeIds    使用的房型id array(11,22,...)
     * @param  array   $disableDates    禁用具体日期 array('2018-01-02','2018-01-03'...)
     * @param  int   $useMan    使用人群 1=全部 2=会员 3=非会员
     * @param  int   $useNumber    每个账号对该优惠券最多可领取次数
     * @param  int   $roomType    房间类型 1=间夜房 2=钟点房 3=长租房
     */
    public function editCoupon($couponId, $name, $startDate, $endDate, $week, $roomTypeIds, $disableDates, $useMan, $useNumber, $roomType) {

        // 校验时间合法性
        if (!isBeforeTime($startDate, $endDate, true)) {
            returnJson(403, 317, 'error');
        }

        if (is_array($week)) {
            $week = implode(',', $week);
        }

        $hotelCouponModel = D('HotelCoupon');
        $hotelCouponRoomTypeModel = D('HotelCouponRoomType');
        $hotelCouponDisableDateModel = D('HotelCouponDisableDate');

        $hotelCouponInfo = $hotelCouponModel->getCouponByIds($couponId);
        $number = $hotelCouponInfo[0]['number'];
        // 优惠券领取数量不能大于优惠券数量
        if ($number != 0 && $useNumber > $number) {
            returnJson(403, 1002);
            return;
        }

        // 比较需要新增或修改数据
        $roomTypeData = $hotelCouponRoomTypeModel->getInfoByCouponId($couponId);
        $roomTypeData = getArrayValueAsIndex($roomTypeData, 'roomtype_id');
        $oldRoomTypeIds = array_column($roomTypeData, 'roomtype_id');

        $addRoomTypeIds = array_diff($roomTypeIds, $oldRoomTypeIds);
        $editRoomTypeIds = array_diff($oldRoomTypeIds, $roomTypeIds);

        // 构造添加数据
        $addRoomTypeIdArray = array();
        if (!empty($addRoomTypeIds)) {
            foreach ($addRoomTypeIds as $key => $roomTypeId) {
                $addRoomTypeIdArray[] = array(
                    'coupon_id' => $couponId,
                    'roomtype_id' => $roomTypeId,
                );
            }
            unset($roomTypeId);
        }

        // 构造修改数据
        $editRoomTypeIdArray = array();
        if (!empty($editRoomTypeIds)) {
            foreach ($editRoomTypeIds as $key => $roomTypeId) {
                $editRoomTypeIdArray[] = array(
                    'id' => $roomTypeData[$roomTypeId]['id'],
                    'isdelete' => IS_DELETE,
                );
            }
            unset($roomTypeId);
        }

        // 比较需要新增或修改数据
        $addDisableDateArray = array();
        $editDisableDateArray = array();
        foreach ($disableDates as $key => &$dates) {
            $dates = strtotime(date('Y-m-d', strtotime($dates)));
        }
        unset($dates);

        $disableDateData = $hotelCouponDisableDateModel->getDateByCouponId($couponId);
        $disableDateData = getArrayValueAsIndex($disableDateData, 'date');
        $oldDisableDateDatas = array_column($disableDateData, 'date');

        $addDisableDate = array_diff($disableDates, $oldDisableDateDatas);
        $editDisableDate = array_diff($oldDisableDateDatas, $disableDates);

        // 构造添加数据
        if (!empty($addDisableDate)) {
            foreach ($addDisableDate as $key => $dates) {
                $addDisableDateArray[] = array(
                    'coupon_id' => $couponId,
                    'date' => $dates,
                );
            }
            unset($dates);
        }

        // 构造修改数据
        if (!empty($editDisableDate)) {
            foreach ($editDisableDate as $key => $dates) {
                $editDisableDateArray[] = array(
                    'id' => $disableDateData[$dates]['id'],
                    'isdelete' => IS_DELETE,
                );
            }
            unset($dates);
        }

        $hotelCouponModel->startTrans();
        $commit = true;

        $saveResult = $hotelCouponModel->saveCoupon($couponId, $name, $startDate, $endDate, $week, $useMan, $useNumber, $roomType);
        if ($saveResult === false) {
            $commit = false;
        }

        // 添加房型
        if ($commit && !empty($addRoomTypeIdArray)) {
            $addResult = $hotelCouponRoomTypeModel->addCouponRoomType($addRoomTypeIdArray);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        // 修改房型
        if ($commit && !empty($editRoomTypeIdArray)) {
            foreach ($editRoomTypeIdArray as $key => $roomTypeArray) {
                $saveResult = $hotelCouponRoomTypeModel->editCouponRoomType($roomTypeArray['id'], $roomTypeArray['isdelete']);
                if ($saveResult === false) {
                    $commit = false;
                    break;
                }
            }
            unset($roomTypeArray);
        }

        // 添加禁用日期
        if ($commit && !empty($addDisableDateArray)) {
            $addResult = $hotelCouponDisableDateModel->addCouponDisableDate($addDisableDateArray);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        // 修改禁用日期
        if ($commit && !empty($editDisableDateArray)) {
            foreach ($editDisableDateArray as $key => $disableArray) {
                $saveResult = $hotelCouponDisableDateModel->editCouponDisableDate($disableArray['id'], $disableArray['isdelete']);
                if ($saveResult === false) {
                    $commit = false;
                    break;
                }
            }
            unset($disableArray);
        }

        //事务提交回滚
        if ($commit) {
            $hotelCouponModel->commit();
            return true;
        } else {
            $hotelCouponModel->rollback();
            return false;
        }
    }

    /**
     * 删除优惠券
     * @modify wenhui 2017-01-02    创建
     * @param  int   $couponId    优惠券ID
     */
    public function deleteCoupon($couponId) {

        $userCouponModel = D('UserCoupon');
        $hotelCouponModel = D('HotelCoupon');
        $hotelCouponRoomTypeModel = D('HotelCouponRoomType');
        $hotelCouponDisableDateModel = D('HotelCouponDisableDate');

        $hotelCouponModel->startTrans();
        $commit = true;

        $result = $hotelCouponModel->deleteCoupon($couponId);
        if ($result === false) {
            $commit = false;
        }

        if ($commit) {
            $result = $hotelCouponRoomTypeModel->deleteCouponRoomType($couponId);
            if ($result === false) {
                $commit = false;
                break;
            }
        }

        if ($commit) {
            $result = $hotelCouponDisableDateModel->deleteCouponDisableDate($couponId);
            if ($result === false) {
                $commit = false;
                break;
            }
        }

        if ($commit) {
            $result = $userCouponModel->saveUserCouponType($couponId, USER_COUPON_CANCELED);
            if ($result === false) {
                $commit = false;
                break;
            }
        }

        //事务提交回滚
        if ($commit) {
            $hotelCouponModel->commit();
            return true;
        } else {
            $hotelCouponModel->rollback();
            return false;
        }
    }

    /**
     * 获取优惠券
     * @modify wenhui 2017-01-02    创建
     * @param  int   $hotelId    客栈ID
     */
    public function getCoupon($hotelId, $couponId = null) {
        $hotelCouponModel = D('HotelCoupon');
        $hotelCouponRoomTypeModel = D('HotelCouponRoomType');
        $hotelCouponDisableDateModel = D('HotelCouponDisableDate');
        $userCouponModel = D('UserCoupon');

        if (!is_null($couponId)) {
            $couponData = $hotelCouponModel->getCouponByIds($couponId);
            $couponIds = $couponId;
        } else {
            $couponData = $hotelCouponModel->getCoupon($hotelId);
            $couponIds = array_column($couponData, 'id');
        }

        if (empty($couponData)) {
            return [];
        }

        $couponRoomTypeData = $hotelCouponRoomTypeModel->getCouponRoomType($couponIds);
        $couponRoomTypeData = getArrayValueAsIndex($couponRoomTypeData, 'coupon_id', true);

        $couponDisableDate = $hotelCouponDisableDateModel->getCouponDisableDate($couponIds);
        $couponDisableDate = getArrayValueAsIndex($couponDisableDate, 'coupon_id', true);
        foreach ($couponDisableDate as $couponId => &$couponDisableDateItem) {
            foreach ($couponDisableDateItem as $key => &$couponDisable) {
                unset($couponDisable['id']);
                $couponDisable['date'] = date('Y-m-d', $couponDisable['date']);
            }
            unset($couponDisable);
            $couponDisableDate[$couponId] = my_sort($couponDisableDate[$couponId], 'date');
        }
        unset($couponDisableDateItem);

        // 获取客栈房型
        $roomTypeBookLogic = A('Common/RoomTypeBook', 'Logic');
        $roomTypeInfo = $roomTypeBookLogic->getInfo($hotelId);
        $roomTypeIdArray = array_column($roomTypeInfo, 'id');

        // 处理数据
        $data = array();
        foreach ($couponData as $key => $coupon) {
            // 已使用数量
            $couponUsed = $userCouponModel->getCouponTotal($coupon['id'], USER_COUPON_USED);
            // 已领取数量
            $getCouponNumber = $userCouponModel->getCouponTotal($coupon['id']);

            $week = !empty($coupon['week']) ? explode(',', $coupon['week']) : array();
            $couponDate = isset($couponDisableDate[$coupon['id']]) ? $couponDisableDate[$coupon['id']] : array();
            $couponRoomType = isset($couponRoomTypeData[$coupon['id']]) ? $couponRoomTypeData[$coupon['id']] : array();
            $data[] = array(
                'couponId' => $coupon['id'],
                'hotelId' => $coupon['hotelentity_id'],
                'couponName' => $coupon['name'],
                'couponNo' => $coupon['no'],
                'couponType' => $coupon['type'],
                'couponPrice' => (float)$coupon['price'],
                'couponDiscount' => (float)$coupon['discount'],
                'couponNumber' => $coupon['number'],
                'couponUsed' => $couponUsed[0]['coupontotal'],
                'getCouponNumber' => $getCouponNumber[0]['coupontotal'],
                'couponStart' => date('Y/m/d', strtotime($coupon['startdate'])),
                'couponEnd' => date('Y/m/d', strtotime($coupon['enddate'])),
                'couponWeek' => $week,
                'couponUseMan' => $coupon['crowd'],
                'couponRoomType' => $coupon['roomtype'],
                'couponMinusPrice' => (float)$coupon['minus_price'],
                'couponReceiveTotal' => $coupon['receive_number'],
                'couponDate' => $couponDate,
                'couponRoomTypeData' => $couponRoomType,
                'isOutDate' => substr($coupon['enddate'], 0, 10) >= date('Y-m-d') ? false : true,
                'isAllRoomType' => count($roomTypeIdArray) == count($couponRoomType) ? true : false,
                'createtime' => $coupon['createtime'],
            );
        }
        unset($coupon);

        return $data;
    }

    /**
     * 获取优惠券领取记录
     * @modify wenhui 2017-01-02    创建
     * @param  int   $hotelId    客栈ID
     * @param  int   $couponId    优惠券ID
     */
    public function getHotelUserCoupon($hotelId, $couponId) {
        $hotelCouponModel = D('HotelCoupon');
        $userCouponModel = D('UserCoupon');
        $userLoginModel = D('UserLogin');
        $orderRoomModel = D('OrderRoom');

        $userCouponInfo = $userCouponModel->getUserCouponByCouponId($couponId);
        if (empty($userCouponInfo)) {
            return array();
        }

        $userIds = array_unique(array_column($userCouponInfo, 'userlogin_id'));
        $userInfo = $userLoginModel->getInfoByUserIds($userIds);
        $userInfo = getArrayValueAsIndex($userInfo, 'id');

        // 获取客栈优惠券信息
        $hotelCouponData = $hotelCouponModel->getCouponByIds($couponId);

        // 处理数据
        $data = array();
        foreach ($userCouponInfo as $key => $userCoupon) {
            $orderNumber = '';
            if ($userCoupon['orderinfo_id'] != 0) {
                $orderRoom = $orderRoomModel->getInfoByOrder($userCoupon['orderinfo_id'], false);
                $orderNumber = encodeOrderNumber($orderRoom[0]['id'], 'MZ');
            }
            // 优惠券存在订单 并且优惠券已过期
            if ($userCoupon['orderinfo_id'] != 0 && in_array($userCoupon['type'], [USER_COUPON_OUTDATED])) {
                //$isChangeCouponType = false;
                $isUserCouponUsed = false;
                foreach ($orderRoom as $key => $orderRoomItem) {
                    if ($orderRoomItem['status'] == ORDER_OUTDATED) {
                        $redisOrderRecordInfo = $orderRoomModel->getInfoInRedisByHotelRoomOrderRoom($hotelId, null, $orderRoomItem['id']);
                        if (!empty($redisOrderRecordInfo)) {
                            $isUserCouponUsed = true;
                        }
                    }

                    // 已支付 已入住 已退房订单 则优惠券改成已使用
                    /*if (in_array($orderRoomItem['status'], [ORDER_PAYED,ORDER_CHECKINED,ORDER_CHECKOUTED])) {
                        $isChangeCouponType = true;
                    }*/
                }
                unset($orderRoomItem);

                // 已过期有效订单 则优惠券改成已使用
                if ($isUserCouponUsed) {
                    $userCoupon['type'] = USER_COUPON_USED;
                }

                // 优惠券存在订单 订单已过期的订单号为空
                if (!$isUserCouponUsed) {
                    $orderNumber = '';
                }
            }

            // 把用户有效已过期的优惠券改成 去使用
            if ($userCoupon['type'] == USER_COUPON_OUTDATED) {
                $userCoupon['type'] = date('Y-m-d', strtotime($hotelCouponData[0]['enddate'])) >= date('Y-m-d') ? USER_COUPON_NOT_USE : USER_COUPON_OUTDATED;
            }

            $name = !empty($userInfo[$userCoupon['userlogin_id']]['name']) ? $userInfo[$userCoupon['userlogin_id']]['name'] : $userInfo[$userCoupon['userlogin_id']]['mobile'];
            $item = array(
                'name' => $name,
                'mobile' => '+'.$userInfo[$userCoupon['userlogin_id']]['areacode'].' '.$userInfo[$userCoupon['userlogin_id']]['mobile'],
                'getDate' => date('Y-m-d', strtotime($userCoupon['createtime'])),
                'userCouponType' => $this->userCouponType[LANG_SET][$userCoupon['type']],
                'orderNumber' => $orderNumber,
                'outDate' => date('Y-m-d', strtotime($hotelCouponData[0]['enddate'])),
            );

            array_push($data, $item);
        }
        unset($userCoupon);

        return $data;
    }
}
